package cn.tradewin.advisor.commons.util;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;

import cn.tradewin.advisor.commons.model.WeekDay;

public class CalendarUtil {

	public static final String DEFAULT_PATTERN = "yyyyMMdd";
	
	public static final String DEFAULT_CALENDAR = "TWD_DEV";
	
	public static List<WeekDay> getAllWeekendDays(String year, String pattern) {
		if (StringUtils.isEmpty(pattern)) {
			pattern = DEFAULT_PATTERN;
		}
		List<WeekDay> days = CollectionFactory.newList();
		DateTime dt = new DateTime(year);
		DateTime min = dt.dayOfYear().withMinimumValue();
		DateTime max = dt.dayOfYear().withMaximumValue();
		dt = min;
		do {
			switch (dt.getDayOfWeek()) {
			case DateTimeConstants.SUNDAY:
				days.add(new WeekDay(dt.toString(pattern),
						DateTimeConstants.SUNDAY));
				break;
			case DateTimeConstants.SATURDAY:
				days.add(new WeekDay(dt.toString(pattern),
						DateTimeConstants.SATURDAY));
				break;
			default:
				break;
			}
			dt = dt.plusDays(1);
		} while (dt.compareTo(max) <= 0);
		return days;
	}

	public static List<WeekDay> getAllWeekDays(String year, String pattern) {
		if (StringUtils.isEmpty(pattern)) {
			pattern = DEFAULT_PATTERN;
		}
		List<WeekDay> days = CollectionFactory.newList();
		DateTime dt = new DateTime(year);
		DateTime min = dt.dayOfYear().withMinimumValue();
		DateTime max = dt.dayOfYear().withMaximumValue();
		dt = min;
		do {
			switch (dt.getDayOfWeek()) {
			case DateTimeConstants.SUNDAY:
				days.add(new WeekDay(dt.toString(pattern),DateTimeConstants.SUNDAY));
				break;
			case DateTimeConstants.MONDAY:
				days.add(new WeekDay(dt.toString(pattern),DateTimeConstants.MONDAY));
				break;
			case DateTimeConstants.TUESDAY:
				days.add(new WeekDay(dt.toString(pattern),DateTimeConstants.TUESDAY));
				break;
			case DateTimeConstants.WEDNESDAY:
				days.add(new WeekDay(dt.toString(pattern),DateTimeConstants.WEDNESDAY));
				break;
			case DateTimeConstants.THURSDAY:
				days.add(new WeekDay(dt.toString(pattern),DateTimeConstants.THURSDAY));
				break;
			case DateTimeConstants.FRIDAY:
				days.add(new WeekDay(dt.toString(pattern),DateTimeConstants.FRIDAY));
				break;
			case DateTimeConstants.SATURDAY:
				days.add(new WeekDay(dt.toString(pattern),DateTimeConstants.SATURDAY));
				break;
			default:
				break;
			}
			dt = dt.plusDays(1);
		} while (dt.compareTo(max) <= 0);
		return days;
	}
	
	public static String format(Date date, String pattern) {
		if (StringUtils.isEmpty(pattern)) {
			pattern = DEFAULT_PATTERN;
		}
		DateTime dt = new DateTime(date);
		return dt.toString(pattern);
	}
}
